<template>
  <div class="im-project">
    <el-dialog
      v-model="visible"
      title="批量导入项目（B类）"
      destroy-on-close
      width="600px"
      @close="handleCancel"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="doc-dia content"
      >
        <el-form-item prop="defaultFileList" label="上传文件">
          <el-upload
            name="uploadFile"
            drag
            ref="upload"
            :accept="acceptXlsxTypes"
            action="javascript:void(0);"
            :on-change="handleChange"
            :on-error="handleError"
            :before-upload="beforeXmlUpload"
            :auto-upload="false"
            :http-request="handleUpload"
            :show-file-list="false"
            :file-list="formData.defaultFileList"
          >
            <div class="el-upload__text">
              <div
                class="download-wrap"
                v-if="formData.defaultFileList?.length"
              >
                <p
                  class="download-text"
                  v-for="(item, index) in formData.defaultFileList"
                  :key="index"
                  @click.stop="handlePreview(item)"
                >
                  <i class="snowfont icon-wendang"></i>
                  <el-link :underline="false">{{ item?.name }}</el-link>
                  <i
                    class="snowfont icon-shanchu"
                    @click.stop="handleRemove"
                  ></i>
                  <i class="iconfont team-iconshanchu'"></i>
                </p>
              </div>

              <div v-else><em>点击上传 </em>或拖拽文件到此区域上传</div>
              <div class="el-upload__tip">
                项目导入模板：<span @click.stop="downLoad">{{ fileName }}</span>
              </div>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSure">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, defineEmits } from "vue";
import { projectTemplateList } from "/@/api/projects";
import { postDictList } from "/@/api/home";
import {
  acceptXlsxTypes,
  beforeXmlUpload,
  handlePreview,
  handleError,
  fileToBase64,
  base64ToFile
} from "/@/utils/file";
const formRef = ref<HTMLFormElement | null>(null) as any;
const upload = ref<HTMLFormElement | null>(null) as any;
const emit = defineEmits(["cancel", "submit"]);
let formData = ref({
  projectTmpId: "",
  projectTmpName: "",
  projectTmpInfo: "" as any,
  projectTypeInfo: {
    dicValue: "B类",
    dicCode: "B0"
  },
  projectTypeName: "",
  projectTypeCode: "",
  defaultFileList: [],
  defaultFileListArr: []
});
const visible = ref(true);
const templateList = ref([]);
const projectTypeList = ref([]);
const fileName = "工程项目批量导入模版.xlsx";
const formRules = {
  defaultFileList: [
    { required: true, message: "请上传文件", trigger: "change" }
  ],
  projectTypeInfo: [
    { required: true, message: "请选择项目类型", trigger: "change" }
  ],
  projectTmpInfo: [
    { required: true, message: "请选择项目模板", trigger: "change" }
  ]
};
const handleCancel = () => {
  emit("cancel");
};

const handleSure = async () => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (isValid) {
    upload.value.submit();
  }
};

const handleRemove = () => {
  formData.value.defaultFileList = [];
};

let fileCache = null;
const handleChange = (file, fileList) => {
  formData.value.defaultFileList = [fileList[fileList.length - 1]];
  fileToBase64(file).then(result => {
    fileCache = result;
  });
  formRef.value.clearValidate();
};

const handleUpload = params => {
  let cacheFile = base64ToFile(
    fileCache,
    formData.value.defaultFileList[0].name
  );
  formData.value.defaultFileList[0].raw = cacheFile;
  const form = new FormData();
  form.append("uploadFile", params.file);
  form.append("projectTypeCode", "B0");
  emit("submit", form);
};

// 模板类型
const initTemplateTypeList = async code => {
  try {
    const { data } = await projectTemplateList({
      isOriginal: "1",
      projectTemplateNameLike: "",
      projectTmpTypeCode: code || "",
      createUserNameLike: "",
      createTimeStrStart: "",
      createTimeStrEnd: "",
      pageNum: 1,
      pageSize: 0
    });
    templateList.value = data.list || [];
  } catch (err) {
    console.log(err);
  }
};

// 项目类型
const initProjectTypeList = async () => {
  try {
    const { data } = await postDictList({ dicType: "thd_pro_type" });
    projectTypeList.value = data || [];
    projectTypeList.value = projectTypeList.value.filter(
      item => item.dicCode === "B"
    );
  } catch (err) {
    console.log(err);
  }
};

const downLoad = async () => {
  console.log(`${location.origin}${location.pathname}/${fileName}`);
  window.open(`${location.origin}${location.pathname}/${fileName}`);
};

onMounted(() => {
  initProjectTypeList();
  initTemplateTypeList("B");
});
defineExpose({ handleRemove });
</script>
<style scoped lang="scss">
.im-project {
  .doc-dia {
    :deep .el-upload {
      width: 100%;
    }
    :deep .el-upload-dragger {
      width: 100%;
      height: auto;
      padding: 40px 20px;
      background: #fdfdff;
      border-radius: 4px;
      .el-upload__text {
        font-size: 12px;
        color: #494c53;
        .download-wrap {
          display: flex;
          justify-content: center;
          .download-text {
            display: flex;
            align-items: center;
            text-align: center;
            color: #5298ff;
            a {
              margin: 0 6px;
              font-size: 14px;
              color: #5298ff;
            }
            .icon-wendang {
              font-size: 16px;
            }
            .icon-shanchu {
              color: #e45d5d;
              font-size: 16px;
            }
          }
        }
      }
    }
    .el-upload__tip {
      line-height: 20px;
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #8895b7;
      margin-top: 0;
      span:hover {
        color: #5298ff;
      }
    }
  }
  :deep .content {
    padding-right: 46px;
  }
}
</style>
